package com.dhecp.project.storage.service.impl;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.project.common.domain.ModuleNidAndBid;
import com.dhecp.project.common.mapper.ModuleNidAndBidMapper;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.storage.domain.DeliveryBox;
import com.dhecp.project.storage.domain.DeliveryBoxDetail;
import com.dhecp.project.storage.domain.DeliveryLogistics;
import com.dhecp.project.storage.domain.DeliveryLogisticsDetail;
import com.dhecp.project.storage.enums.DeliveryBoxEnum;
import com.dhecp.project.storage.enums.DeliveryLogisticsEnum;
import com.dhecp.project.storage.enums.DeliveryRequestEnum;
import com.dhecp.project.storage.mapper.DeliveryBoxDetailMapper;
import com.dhecp.project.storage.mapper.DeliveryBoxMapper;
import com.dhecp.project.storage.mapper.DeliveryLogisticsDetailMapper;
import com.dhecp.project.storage.mapper.DeliveryLogisticsMapper;
import com.dhecp.project.storage.mapper.DeliveryRequestMapper;
import com.dhecp.project.storage.service.DeliveryBoxService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 查询海外发货申请单 服务层
 */
@Service
public class DeliveryBoxServicelmpl extends BaseModuleServiceImpl implements DeliveryBoxService {


    @Autowired
    private DeliveryRequestMapper deliveryRequestMapper;
    @Autowired
    private DeliveryBoxMapper deliveryBoxMapper;
    @Autowired
    private DeliveryBoxDetailMapper deliveryBoxDetailMapper;
    @Autowired
    private DeliveryLogisticsMapper deliveryLogisticsMapper;
    @Autowired
    private DeliveryLogisticsDetailMapper deliveryLogisticsDetailMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private ModuleNidAndBidMapper moduleNidAndBidMapper;

    /**
     * 查询查询海外发货申请单
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<DeliveryBox> queryList(Map<String, Object> params) throws Exception {
    	
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句

        if (params.get("field") == null || params.get("field") == ""){
            String orderBy = "t1.createTime DESC";
            PageUtils.startPageOrder(orderBy);
        }else{
            PageUtils.startPage();
        }
        return deliveryBoxMapper.select(params);
    }

    /**
     * 查询海外发货申请单-明细
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<DeliveryBoxDetail> querySonListByBid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        String orderBy = "t1.createTime DESC";
        PageUtils.startPageOrder(orderBy);
        return deliveryBoxDetailMapper.select(params);
    }
    /**
     * 查询查询海外发货申请单
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public DeliveryBox queryFirstRecord(Map<String, Object> params) throws Exception {

        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return deliveryBoxMapper.selectFirstRecordByNid(params);
    }

	@Override
	public DeliveryBox queryByBid(String bid) {
		return deliveryBoxMapper.findByBid(bid);
	}

	@Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public AjaxResult saveData(Map<String, Object> params) throws Exception {
		
		String bid = params.get("bid").toString();
		if (bid == null || bid.length() == 0) {
			return AjaxResult.error("单号为空，无法操作！");
		}
		
		DeliveryBox deliveryBoxOld = deliveryBoxMapper.findByBid(bid);
		if (!deliveryBoxOld.getStateName().equals(DeliveryBoxEnum.StateName.INIT.value)) {
			return AjaxResult.error("非待审核，无法操作！");
		}
		
		// 保存明细数据
		String detailArr = params.get("detailArr").toString();
		JSONArray detailJA = JSON.parseArray(detailArr);
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			DeliveryBoxDetail deliveryBoxDetail = JSON.parseObject(detailJO.toJSONString(), DeliveryBoxDetail.class);
			deliveryBoxDetailMapper.update(deliveryBoxDetail);
		}
		
		return AjaxResult.success("操作成功");
	}
	
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateState(String bid) throws Exception {
    	
    	DeliveryBox deliveryBox = deliveryBoxMapper.findByBid(bid);
    	if (!deliveryBox.getStateName().equals(DeliveryBoxEnum.StateName.INIT.value)) {
			return AjaxResult.error("该单据非待审核状态，无法重复操作");
		}
    	
    	// 品名总数
    	Integer numProNameAll = 0;
    	List<String> listProNameUnique = new ArrayList<String>();
    	List<DeliveryBoxDetail> listDeliveryBoxDetail = deliveryBoxDetailMapper.listByBidBox(deliveryBox.getBid());
    	// 品名字符串，用,隔开
    	for(DeliveryBoxDetail deliveryBoxDetail : listDeliveryBoxDetail) {
    		
    		String nameUnique = deliveryBoxDetail.getProductNameCn() + "-" + deliveryBoxDetail.getProductMaterialCn() + "-" + deliveryBoxDetail.getProductCodeHs();
    		if (listProNameUnique.contains(nameUnique)) {
				continue;
			} else {
				listProNameUnique.add(nameUnique);
				numProNameAll++;
			}
    	}
    	// 计重 = MAX（A1，单票起重），A1=MAX（单箱装箱实重，单箱装箱抛重，单箱起重）所有箱子先加起来，再进行约分（约分取整）
    	BigDecimal weightCal = BigDecimal.ZERO;
    	// 材质名称，格式如：'木质','纸质'
    	for(DeliveryBoxDetail deliveryBoxDetail : listDeliveryBoxDetail) {
    		weightCal = weightCal.add(deliveryBoxDetail.getSizeWeight());
    	}
    	weightCal = weightCal.add(new BigDecimal(0.5)).setScale(0, BigDecimal.ROUND_HALF_UP);
    	
        String stateName = DeliveryBoxEnum.StateName.SUCCESS.value;
        deliveryBoxMapper.updateState(bid,  stateName);

        //新增装箱物流
        DeliveryLogistics deliveryLogistics = new DeliveryLogistics();
        {

            Map<String, Object> params1 = new HashMap<String, Object>();
            params1.put("moduleTable", ModuleTable.DELIVERY_LOGISTICS);
            ModuleNidAndBid moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params1);    //有事务控制，制单异常不跳过单号

            deliveryLogistics.setGuid(RandomValueUtils.getGUID());
            deliveryLogistics.setBid(moduleNidAndBid.getBid());
            deliveryLogistics.setBidRequest(deliveryBox.getBidRequest());
            deliveryLogistics.setBidBox(deliveryBox.getBid());
            deliveryLogistics.setNumBox(deliveryBox.getNumAll());
            deliveryLogistics.setNumProName(numProNameAll);
            deliveryLogistics.setStateName(DeliveryLogisticsEnum.StateName.INIT.value);
            deliveryLogistics.setStateRkName(DeliveryLogisticsEnum.StateRkName.INIT.value);
            deliveryLogistics.setWeightCal(weightCal);
            deliveryLogistics.setFreeChannel(deliveryBox.getFreeChannel());
            deliveryLogistics.setWarehousingCharge(deliveryBox.getWarehousingCharge());

            // 材质附加费单价=物流名称 -> 材质列表中最高的材质附加单价
            deliveryLogisticsMapper.insertDeliveryLogistics(deliveryLogistics);
        }
        
        // 新增物流发货单详情
        for(DeliveryBoxDetail deliveryBoxDetail : listDeliveryBoxDetail) {
    		
    		DeliveryLogisticsDetail deliveryLogisticsDetail = new DeliveryLogisticsDetail();
    		deliveryLogisticsDetail.setGuid(RandomValueUtils.getGUID());
    		deliveryLogisticsDetail.setBidLogistics(deliveryLogistics.getBid());
    		deliveryLogisticsDetail.setProductCode(deliveryBoxDetail.getProductCode());
    		deliveryLogisticsDetail.setProductName(deliveryBoxDetail.getProductName());
    		deliveryLogisticsDetail.setProductNameCn(deliveryBoxDetail.getProductNameCn());
    		deliveryLogisticsDetail.setProductMaterialCn(deliveryBoxDetail.getProductMaterialCn());
    		deliveryLogisticsDetail.setProductCodeHs(deliveryBoxDetail.getProductCodeHs());
    		deliveryLogisticsDetail.setBoxNo(deliveryBoxDetail.getBoxNo());
    		deliveryLogisticsDetail.setProductNum(deliveryBoxDetail.getProductNum());
    		deliveryLogisticsDetail.setProductSjNum(0);
    		deliveryLogisticsDetail.setSizeLength(deliveryBoxDetail.getSizeLength());
    		deliveryLogisticsDetail.setSizeWidth(deliveryBoxDetail.getSizeWidth());
    		deliveryLogisticsDetail.setSizeHeight(deliveryBoxDetail.getSizeHeight());
    		deliveryLogisticsDetail.setSizeWeight(deliveryBoxDetail.getSizeWeight());
    		deliveryLogisticsDetail.setWeightVol(deliveryBoxDetail.getWeightVol());
    		deliveryLogisticsDetail.setRemark(deliveryBoxDetail.getRemark());
    		deliveryLogisticsDetail.setStatus(1);
    		deliveryLogisticsDetailMapper.insertDeliveryLogisticsDetail(deliveryLogisticsDetail);
        }
        
//        // 添加转出流水
//        {
//            String vGsBm = "GS0641";
//            String vGsBmP = "GS0608";
//            BigDecimal fJe = new BigDecimal(0);
//            String vJyLx = "仓储服务→手续费";
//            String vBz = "海外仓物流，单号：" + deliveryBox.getBid();
//            String mName = "仓储服务";
//            Integer mType = 1;
//            String mNid = null;
//            String mBid = deliveryBox.getBid();
//            String mGuid = deliveryBox.getGuid();
//            String operatorDept = deliveryRequest.getaDeptName();
//            String operatorPosition = deliveryRequest.getaPosition();
//            String operatorName = deliveryRequest.getaUserName();
//            String operatorUserId = deliveryRequest.getaUser();
//            accountDetailedForCompanyService.insertAccountDetailedForCompany(vGsBm, vGsBmP, fJe, vJyLx, vBz, mName, mType, mNid, mBid, mGuid, operatorDept, operatorPosition, operatorName, operatorUserId);
//        }
//        
//        // 添加转入流水
//        {
//            String vGsBm = "GS0608";
//            String vGsBmP = "GS0641";
//            BigDecimal fJe = new BigDecimal(0);
//            String vJyLx = "仓储服务→手续费";
//            String vBz = "海外仓装箱，单号：" + deliveryBox.getBid();
//            String mName = "仓储服务";
//            Integer mType = 1;
//            String mNid = null;
//            String mBid = deliveryBox.getBid();
//            String mGuid = deliveryBox.getGuid();
//            String operatorDept = deliveryRequest.getaDeptName();
//            String operatorPosition = deliveryRequest.getaPosition();
//            String operatorName = deliveryRequest.getaUserName();
//            String operatorUserId = deliveryRequest.getaUser();
//            accountDetailedForCompanyService.insertAccountDetailedForCompany(vGsBm, vGsBmP, fJe, vJyLx, vBz, mName, mType, mNid, mBid, mGuid, operatorDept, operatorPosition, operatorName, operatorUserId);
//        }
        
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }
	
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult refuse(String bid) throws Exception {
    	
    	DeliveryBox deliveryBox = deliveryBoxMapper.findByBid(bid);
    	if (!deliveryBox.getStateName().equals(DeliveryBoxEnum.StateName.INIT.value)) {
			return AjaxResult.error("该单据非待审核状态，无法重复操作");
		}
    	
    	// 删除装箱单
    	deliveryBoxMapper.deleteByBid(bid);
    	
    	// 删除装箱单详情
    	deliveryBoxDetailMapper.deleteByBidBox(bid);
    	
    	// 更新申请单状态
    	deliveryRequestMapper.updateState(deliveryBox.getBidRequest(), DeliveryRequestEnum.StateName.FLOW.value);
        
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }
}
